service 能夠讓應用程式被使用者存取,也可以讓 pod 與 pod 之間或與資料庫連線,例如:前端跟後端透過 service 連線、後端跟資料庫連線。
前面有提到過 pod 會有自己的 IP,但是在叢集中 pod 只要重新建立後 IP 就會更動,所以要靠 Service 這個元件來幫助各個元件可以互相連線。
k8s 本身並沒有提供相關的網路實作與設計,而是讓使用者在特定的規範下去設計網路。
Service 有三種類型:

service 監聽 node 上的某一 port(ex: 30001),並把從該 port 中收到的請求轉發至 pod 上的 port,讓 pod 得以透過 node port 被外界存取到。
直接來看如何建立 service。
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  type: NodePort
  ports:
  - name: http
    port: 80
    targetPort: 80
    nodePort: 30001
    protocol: TCP
  selector:
    app: my-app
selector:套用在哪些 pod 上type:這邊指定為 NodePort
ports:這邊是一個陣列,可以放入多種 port 的配置(mapping),目前是按照圖的方式配對。
port 設定一樣kubectl create -f nginx-deploy.yaml
kubectl create -f nginx-service.yaml
service/nginx-service created
<none>。kubectl get svc
NAME            TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
kubernetes      ClusterIP   10.96.0.1      <none>        443/TCP        4d22h
nginx-service   NodePort    10.102.5.152   <none>        80:30001/TCP   10s
minikube service nginx-service --url
http://127.0.0.1:51661
❗  Because you are using a Docker driver on darwin, the terminal needs to be open to run it.
http://127.0.0.1:51661

ClusterIP(internal service) 將叢集內的 pods group 起來,提供單一介面給叢集內部去做存取,收到的請求會以隨機的方式轉發至任一 pod。例如:一組 monogodb pods 透過 clusterIP 提供內部其他 pods 存取。
透過此種 service 能有效地在叢集中部署微服務架構,當同組 pods 需要新增或刪減 pods 時,不會影響到 pods 之間的溝通。
例如依照上圖建立一個 service 的設定檔。
apiVersion: v1
kind: Service
metadata:
  name: backend-service
spec:
  type: ClusterIP
  ports:
  - port: 80
    targetPort: 3000
    protocol: TCP
  selector:
    app: my-app
kubectl create -f backend-service.yaml 建立 service。kubectl get svc backend-service 查看。這邊就不列出執行內容了。
service 可以通過雲端供應商的 load balancer 進行存取,例如 Google、AWS 和 Azure 都有各自的原生 load balancer。當 service 的 type 設定為 LoadBalancer 時,NodePort 跟 ClusterIP service 會自動被建立,外界的請求可以透過雲端供應商的 load balancer 轉發至 NodePort 和 ClusterIP service 上。
底下為設定檔範例。
apiVersion: v1
kind: Service
metadata:
  name: app-service
spec:
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 80
    nodePort: 30001
    protocol: TCP
  selector:
    app: my-app